package com.juzhencms.apps.busi.web;



import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.OrganizationService;
import com.juzhencms.apps.busi.service.UserService;

import lombok.extern.slf4j.Slf4j;

import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.MD5Util;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;


@Controller
@RequestMapping("/user")
@Slf4j
public class UserController  extends BaseController{
	
	@Autowired
	private UserService userService;
	
	
	@Autowired
	private OrganizationService organizationService;
	
	//查询所有用户
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		//查询为删除且为非系统管理员的数据
		String where=" where del_flag=0 and is_sys = 0 ";

		where+=" and org_id in("+this.getLoginUser().getSubOrgIds()+") ";
		
		//log.info(this.getLoginUser().getSubOrgIds());
		
		
		//机构筛选条件
		if( StringUtil.isNotNullOrEmpty(request.getParameter("org_id")) && !request.getParameter("org_id").equals("0")){
			/*where+=" and find_in_set(org_id,?) ";
			int org_id = new Integer(request.getParameter("org_id").toString());
			String getOrgIds = organizationService.getOrgIds(org_id);
			whereParamList.add(getOrgIds);*/
			
			//查询单个机构即可，不需要查询下级机构
			where+=" and org_id=? ";
			whereParamList.add(request.getParameter("org_id"));
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		String select=null;
		if(request.getParameter("select")!=null && !request.getParameter("select").toString().trim().equals("") && request.getParameter("selValue")!=null && !request.getParameter("selValue").toString().trim().equals("")){
			select=request.getParameter("select");
			where+=" and "+ select +" like ? ";
			whereParamList.add("%"+request.getParameter("selValue")+"%");
		}
		
		
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		
		//排序参数 
		String sortField="create_time";
		String sortOrder="desc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.user+" "+where+" order by "+sortField+" "+sortOrder+",id desc limit ?,?", whereParamList.toArray());
		String orderby = " order by "+sortField+" "+sortOrder+",id asc ";
		//List dataList = userService.getLists("", where, whereParamList, orderby, pageIndex, pageSize,0);
		
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
				if (row.get("update_time")!=null) {
					Date dateUpdate = (Date)row.get("update_time");
					row.put("update_time",sdf.format(dateUpdate));
				}
			}
			//查询创建人
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Integer create_userid = (Integer) row.get("create_user");
				List createUserList = this.getCommonService().getJdbcDao().querySql("select name from "+DBTable.user+" where id="+create_userid);
				if(createUserList!=null && createUserList.size()>0){
					Map createUser_row=(Map) createUserList.get(0);
					String name=(String) createUser_row.get("name");
					row.put("create_user",name);
				}else{
					row.put("create_user","");
				}
			}
			
		}
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.user+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		//Map countRow = userService.getDetail(" count(id) as count_num ", where, whereParamList.subList(0, whereParamList.size()-2), "",0);	
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		//返回创建人
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		return WebUtil.resultString(data,request);
	}
	
	
	//保存用户
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		
		
		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		String pass=null;
		if(data.get("pass")!=null && !data.get("pass").equals("")){
			pass=data.get("pass").toString();
			//pass=MD5Util.md5(pass);
			int pass_randstr = new Random().nextInt(9999999);
			String newPass=MD5Util.md5(pass+pass_randstr);
			data.put("pass_randstr", pass_randstr);
			data.put("pass", newPass);
			
			//如果设置了密码，同时解除账号锁定
			data.put("login_fail_times", 0);
		}
		
		//机构org_id
		if(StringUtil.isNullOrEmpty(data.get("org_id"))) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "保存失败，请选择所属机构");
			return WebUtil.resultString(result,request);
		} else {
			int org_id = new Integer(data.get("org_id").toString());
			if(org_id <=0) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "保存失败，请选择所属机构");
				return WebUtil.resultString(result,request);
			}
			data.put("org_id",org_id );
			//机构名称  
			Map getOrg = this.getCommonService().getJdbcDao().queryRow("select name from "+DBTable.organization+" where id=? ",new Object[]{org_id});
			String org_name = "";
			if(getOrg!=null && !getOrg.get("name").equals("") ) {
				org_name = getOrg.get("name").toString();
			}
			data.put("org_name",org_name);	
		}
		
		String user=(String) data.get("user");
		Map tmpuser=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where (user=? or mobile=?) and id!=? and del_flag = 0 limit 0,1",new Object[]{user,user,id!=null?id:""});
		if(tmpuser!=null){
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "用户名已存在，请重新输入");
			return WebUtil.resultString(result,request);
		}
		
		String mobile=(String) data.get("mobile");
		if(mobile!=null && !mobile.equals("")) {
			tmpuser=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where (user=? or mobile=?) and id!=? and del_flag = 0 limit 0,1",new Object[]{mobile,mobile,id!=null?id:""});
			if(tmpuser!=null){
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "手机号已存在，请重新输入");
				return WebUtil.resultString(result,request);
			}
		}
		
		
		if(id==null || id.equals("")){
			
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = new Date();
				data.put("create_time", sdf.format(date));
			}
			
			
			
			
			int pass_token = new Random().nextInt(99999);
			data.put("token", pass_token);
			this.getCommonService().getJdbcDao().addObj(DBTable.user, data);
		}else{
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			data.put("update_time", sdf.format(date));
			
			this.getCommonService().getJdbcDao().updateObj(DBTable.user, data, "id");
		}
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}
	
	//用户修改
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
//		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where del_flag=0 and id=?",new Object[]{id});	
		
		String where = " del_flag=0 and id = ? and is_sys = 0 ";	
		List whereParamList = new ArrayList();
		whereParamList.add(new Integer(id));
		Map record = userService.getDetail("  *  ", where, whereParamList, "",0);		
		//
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("pass", null);
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		return WebUtil.resultString(data, request);
	}
	
	//删除用户
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){

		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
			//this.getCommonService().getJdbcDao().updateSql("delete from "+DBTable.member+" where id in ("+tmpVar+")",idArray);
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.user+" set del_flag=1 where id in ("+tmpVar+") and is_sys = 0 ",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	//更新发布状态
	@RequestMapping(value="/updatePublish",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePublish(HttpServletRequest request){
		String num = "1".equals(request.getParameter("publish"))?"0":"1";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.user+" set publish=? where id=?",new Object[]{num,request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	//验证user是否重复
	@RequestMapping(value="/checkUser",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String checkUser(HttpServletRequest request){
		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		String user=(String) data.get("user");
		Map tmpuser=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where user=? and publish=1  and del_flag = 0  limit 0,1",new Object[]{user});
		if(tmpuser!=null){
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "用户名已存在");
			return WebUtil.resultString(result,request);
		}
		return null;
	}
	//获取登陆用户信息
	@RequestMapping(value="/userInfo",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String  getUserInfo(HttpServletRequest request){
		
		
//		HttpSession session=request.getSession();
//		Map loginUser = (Map) session.getAttribute("loginUser");
		
		AdminLoginUser loginUser = userService.getLoginUser();
		Map data=new HashMap();
		if(loginUser!=null){
			String id = ""+loginUser.getId();
			
			
			
//			Map record=this.getCommonService().getJdbcDao().queryRow("select user,name,img,role from "+DBTable.user+" where del_flag=0 and id=?",new Object[]{id});	
			
			String where = " del_flag=0 and id = ? ";	
			List whereParamList = new ArrayList();
			whereParamList.add(new Integer(id));
			Map record = userService.getDetail("  id,user,name,img,role,mobile,weixin_appid,weixin_openid,weixin_follow   ", where, whereParamList, "",0);			
			
			
			//System.out.println(record);
			if(record.get("img")==null || record.get("img").equals("")){
				record.put("img", "default_head.png");
			}
			
			if(record.get("role")!=null || !record.get("role").equals("")){
				String[] roleStrArr=record.get("role").toString().split(",");
				List roleVarList=new ArrayList();
				List roleIdList=new ArrayList();
				
				for(int i=0;i<roleStrArr.length;i++){
					if(roleStrArr[i]!=null && !roleStrArr[i].equals("")){
						roleVarList.add("?");
						roleIdList.add(roleStrArr[i]);
					}
				}
				
				//LogTool.print(roleIdList, this.getClass());
				
				if(roleIdList.size()>0){
					List roleList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.role+" where id in("+org.apache.commons.lang3.StringUtils.join(roleVarList.toArray(), ",")+")", roleIdList.toArray());
					if(roleList!=null && roleList.size()>0){
						String roleText="";
						for(int i=0;i<roleList.size();i++){
							Map roleRecord=(Map)roleList.get(i);
							if(i<roleList.size()-1)
								roleText+=roleRecord.get("name").toString()+",";
							else
								roleText+=roleRecord.get("name").toString();
						}
						record.put("roleText", roleText);
					}
				}
			}
			if(record.get("roleText")==null || record.get("roleText").equals("")){
				record.put("roleText", "无");
			}
			
			data.put("data", record);
			
			
			//查询系统公账号名称及二维码信息
			Map weixinData=new HashMap();
			weixinData.put("weixinAccount", Config.getValue("weixin.account"));
			weixinData.put("weixinQrcodeImg", Config.getUploadUrlPath()+"/"+Config.getValue("weixin.qrcodeImg"));
			
			data.put("weixinData", weixinData);
		}
		
		
		
		return WebUtil.resultString(data,request);
	}
	
	//修改密码
	@RequestMapping(value="/editpwd",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String  editPwd(HttpServletRequest request,HttpServletResponse response){
		
		AdminLoginUser loginUser = this.getLoginUser();
		String id = ""+loginUser.getId();
		
		if (loginUser !=null) {
			
			Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
			
			Map oldUserRecord=this.getCommonService().getJdbcDao().queryRow("select pass,pass_randstr from "+DBTable.user+" where id=?", new Object[] {id});
			if(oldUserRecord==null) {
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "用户不存在");
				
				return WebUtil.resultString(result,request);
			}
			
			
			//校验原密码
			String oldpass=(String) data.get("oldpass");
			if(oldpass!=null && !oldpass.equals("")){
				//oldpass=MD5Util.md5(oldpass);
				
				
				String old_pass_randstr = "";
				if(oldUserRecord.get("pass_randstr")!=null) {
					old_pass_randstr=oldUserRecord.get("pass_randstr").toString();
				}
				String old_pass="";
				if(oldUserRecord.get("pass")!=null) {
					old_pass=oldUserRecord.get("pass").toString();
				}
				
				
				oldpass=MD5Util.md5(oldpass+old_pass_randstr);
				if(!oldpass.equals(old_pass)) {
					Map result=new HashMap();
					result.put("result",0);
					result.put("msg", "旧密码输入不正确");
					
					return WebUtil.resultString(result,request);
				}
			}else {
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "请输入原密码");
				
				return WebUtil.resultString(result,request);
			}
			
			
			String pass=(String) data.get("pass");
			if ((String)data.get("repass") != null && !((String)data.get("repass")).equals("") )  {
				if (!data.get("repass").equals(pass)) {
					Map result=new HashMap();
					result.put("result",0);
					result.put("msg", "两次输入密码不一致，请重新输入");
					
					return WebUtil.resultString(result,request);
				}
			}
			
			if(pass!=null && !pass.equals("")){
				//pass=MD5Util.md5(pass);
				int pass_randstr = new Random().nextInt(9999999);
				String newPass=MD5Util.md5(pass+pass_randstr);
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.user+" set pass=? , pass_randstr=? where id=?",new Object[]{newPass,pass_randstr,id});
				this.getUserService().logout(request, response);
				
				//清空此用户缓存，暂时未使用
				//this.getUserService().cleanUserCache(this.getLoginUserId());
				
				
			}else {
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "新密码不符合要求");
				
				return WebUtil.resultString(result,request);
			}
			
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "密码修改成功，请重新登录");
		
		
		
		return WebUtil.resultString(result,request);
	}
	
	
	
	
}
